import 'package:flutter/material.dart';

/// 分享卡片配置
class ShareCardConfig {
  /// 是否显示时间
  final bool showTime;

  /// 是否显示文件信息
  final bool showFileInfo;

  /// 是否显示标签
  final bool showTags;

  /// 是否显示操作按钮
  final bool showActions;

  /// 是否紧凑模式
  final bool compact;

  /// 最大行数
  final int maxLines;

  /// 边距
  final EdgeInsets? margin;

  /// 内边距
  final EdgeInsets? padding;

  const ShareCardConfig({
    this.showTime = true,
    this.showFileInfo = true,
    this.showTags = true,
    this.showActions = true,
    this.compact = false,
    this.maxLines = 3,
    this.margin,
    this.padding,
  });
}

/// 分享卡片数据接口
abstract class ShareCardData {
  String get id;
  String get title;
  String? get content;
  String get type;
  String get createdAt;
  String get updatedAt;
  List<String> get tags;
  List<String> get filePaths;
  bool get isFavorite;

  /// 获取类型图标
  IconData get typeIcon;

  /// 获取类型颜色
  Color get typeColor;
}

/// 通用分享卡片组件
class ShareCardWidget extends StatelessWidget {
  /// 分享数据
  final ShareCardData data;

  /// 配置
  final ShareCardConfig config;

  /// 点击回调
  final VoidCallback? onTap;

  /// 收藏切换回调
  final VoidCallback? onFavoriteToggle;

  /// AI分析回调
  final VoidCallback? onAIAnalysis;

  /// 更多操作回调
  final VoidCallback? onMoreActions;

  /// 是否选中
  final bool isSelected;

  /// 选择模式
  final bool selectionMode;

  /// 选择切换回调
  final VoidCallback? onToggleSelection;

  /// 高亮查询
  final String? highlightQuery;

  const ShareCardWidget({
    Key? key,
    required this.data,
    this.config = const ShareCardConfig(),
    this.onTap,
    this.onFavoriteToggle,
    this.onAIAnalysis,
    this.onMoreActions,
    this.isSelected = false,
    this.selectionMode = false,
    this.onToggleSelection,
    this.highlightQuery,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: config.margin ??
          const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: BorderRadius.circular(config.compact ? 12 : 16),
        border: isSelected
            ? Border.all(color: Theme.of(context).primaryColor, width: 2)
            : Border.all(
                color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
              ),
        boxShadow: [
          BoxShadow(
            color: Theme.of(context).shadowColor.withOpacity(0.05),
            blurRadius: config.compact ? 4 : 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: selectionMode ? onToggleSelection : onTap,
          borderRadius: BorderRadius.circular(config.compact ? 12 : 16),
          child: Padding(
            padding: config.padding ?? EdgeInsets.all(config.compact ? 12 : 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildHeader(context),
                if (!config.compact) const SizedBox(height: 12),
                _buildContent(context),
                if (config.showTags && data.tags.isNotEmpty) ...[
                  SizedBox(height: config.compact ? 8 : 12),
                  _buildTags(context),
                ],
                if (config.showFileInfo && data.filePaths.isNotEmpty) ...[
                  SizedBox(height: config.compact ? 8 : 12),
                  _buildFileInfo(context),
                ],
                if (config.showActions && !selectionMode) ...[
                  SizedBox(height: config.compact ? 8 : 12),
                  _buildActions(context),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader(BuildContext context) {
    return Row(
      children: [
        // 类型图标
        Container(
          width: config.compact ? 32 : 40,
          height: config.compact ? 32 : 40,
          decoration: BoxDecoration(
            color: data.typeColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(config.compact ? 6 : 8),
          ),
          child: Icon(
            data.typeIcon,
            size: config.compact ? 16 : 20,
            color: data.typeColor,
          ),
        ),

        SizedBox(width: config.compact ? 8 : 12),

        // 标题和时间
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTitle(context),
              if (config.showTime) ...[
                const SizedBox(height: 4),
                _buildTime(context),
              ],
            ],
          ),
        ),

        // 选择或收藏图标
        if (selectionMode) ...[
          Icon(
            isSelected ? Icons.check_circle : Icons.radio_button_unchecked,
            color: isSelected ? Theme.of(context).primaryColor : null,
          ),
        ] else if (data.isFavorite) ...[
          Icon(
            Icons.favorite,
            size: config.compact ? 16 : 18,
            color: Colors.red.shade400,
          ),
        ],
      ],
    );
  }

  /// 构建标题
  Widget _buildTitle(BuildContext context) {
    if (highlightQuery != null && highlightQuery!.isNotEmpty) {
      return RichText(
        text: TextSpan(
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
                fontSize: config.compact ? 14 : 16,
              ),
          children: [
            _buildHighlightedText(
              data.title,
              highlightQuery!,
              Theme.of(context).primaryColor,
            )
          ],
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      );
    }

    return Text(
      data.title,
      style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.w600,
            fontSize: config.compact ? 14 : 16,
          ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 构建时间
  Widget _buildTime(BuildContext context) {
    return Text(
      _formatTime(data.createdAt),
      style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Colors.grey.shade600,
            fontSize: config.compact ? 11 : 12,
          ),
    );
  }

  /// 构建内容
  Widget _buildContent(BuildContext context) {
    final content = data.content;

    if (content == null || content.isEmpty) {
      return const SizedBox.shrink();
    }

    if (highlightQuery != null && highlightQuery!.isNotEmpty) {
      return RichText(
        text: TextSpan(
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Colors.grey.shade700,
                height: 1.4,
                fontSize: config.compact ? 13 : 14,
              ),
          children: [
            _buildHighlightedText(
              content,
              highlightQuery!,
              Theme.of(context).primaryColor,
            )
          ],
        ),
        maxLines: config.maxLines,
        overflow: TextOverflow.ellipsis,
      );
    }

    return Text(
      content,
      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
            color: Colors.grey.shade700,
            height: 1.4,
            fontSize: config.compact ? 13 : 14,
          ),
      maxLines: config.maxLines,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 构建标签
  Widget _buildTags(BuildContext context) {
    return Wrap(
      spacing: 6,
      runSpacing: 6,
      children: data.tags.take(3).map((tag) {
        return Container(
          padding: EdgeInsets.symmetric(
            horizontal: config.compact ? 6 : 8,
            vertical: config.compact ? 2 : 4,
          ),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(config.compact ? 8 : 10),
          ),
          child: Text(
            '#$tag',
            style: TextStyle(
              color: Theme.of(context).primaryColor,
              fontSize: config.compact ? 10 : 11,
              fontWeight: FontWeight.w500,
            ),
          ),
        );
      }).toList(),
    );
  }

  /// 构建文件信息
  Widget _buildFileInfo(BuildContext context) {
    final fileCount = data.filePaths.length;

    return Row(
      children: [
        Icon(
          Icons.attach_file,
          size: config.compact ? 14 : 16,
          color: Colors.grey.shade600,
        ),
        const SizedBox(width: 4),
        Text(
          '$fileCount 个文件',
          style: TextStyle(
            color: Colors.grey.shade600,
            fontSize: config.compact ? 11 : 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 构建操作按钮
  Widget _buildActions(BuildContext context) {
    return Row(
      children: [
        const Spacer(),

        // 收藏按钮
        IconButton(
          onPressed: onFavoriteToggle,
          icon: Icon(
            data.isFavorite ? Icons.favorite : Icons.favorite_border,
            size: config.compact ? 16 : 18,
          ),
          color: data.isFavorite ? Colors.red.shade400 : Colors.grey.shade600,
          tooltip: data.isFavorite ? '取消收藏' : '添加收藏',
          padding: EdgeInsets.all(config.compact ? 4 : 8),
          constraints: BoxConstraints(
            minWidth: config.compact ? 32 : 40,
            minHeight: config.compact ? 32 : 40,
          ),
        ),

        // AI分析按钮
        if (onAIAnalysis != null)
          IconButton(
            onPressed: onAIAnalysis,
            icon: Icon(
              Icons.auto_awesome,
              size: config.compact ? 16 : 18,
            ),
            color: Colors.blue.shade600,
            tooltip: 'AI分析',
            padding: EdgeInsets.all(config.compact ? 4 : 8),
            constraints: BoxConstraints(
              minWidth: config.compact ? 32 : 40,
              minHeight: config.compact ? 32 : 40,
            ),
          ),

        // 更多操作按钮
        if (onMoreActions != null)
          IconButton(
            onPressed: onMoreActions,
            icon: Icon(
              Icons.more_vert,
              size: config.compact ? 16 : 18,
            ),
            color: Colors.grey.shade600,
            tooltip: '更多操作',
            padding: EdgeInsets.all(config.compact ? 4 : 8),
            constraints: BoxConstraints(
              minWidth: config.compact ? 32 : 40,
              minHeight: config.compact ? 32 : 40,
            ),
          ),
      ],
    );
  }

  /// 构建高亮文本
  TextSpan _buildHighlightedText(
    String text,
    String query,
    Color highlightColor,
  ) {
    if (query.isEmpty) {
      return TextSpan(text: text);
    }

    final matches = <TextSpan>[];
    final lowerText = text.toLowerCase();
    final lowerQuery = query.toLowerCase();

    int start = 0;
    int index = lowerText.indexOf(lowerQuery);

    while (index != -1) {
      // 添加匹配前的文本
      if (index > start) {
        matches.add(TextSpan(text: text.substring(start, index)));
      }

      // 添加高亮的匹配文本
      matches.add(TextSpan(
        text: text.substring(index, index + query.length),
        style: TextStyle(
          color: highlightColor,
          fontWeight: FontWeight.bold,
          backgroundColor: highlightColor.withOpacity(0.2),
        ),
      ));

      start = index + query.length;
      index = lowerText.indexOf(lowerQuery, start);
    }

    // 添加剩余的文本
    if (start < text.length) {
      matches.add(TextSpan(text: text.substring(start)));
    }

    return TextSpan(children: matches);
  }

  /// 格式化时间
  String _formatTime(String dateTime) {
    try {
      final date = DateTime.parse(dateTime);
      final now = DateTime.now();
      final difference = now.difference(date);

      if (difference.inDays > 0) {
        if (difference.inDays == 1) {
          return '1天前';
        } else if (difference.inDays < 7) {
          return '${difference.inDays}天前';
        } else if (difference.inDays < 30) {
          final weeks = (difference.inDays / 7).floor();
          return '${weeks}周前';
        } else if (difference.inDays < 365) {
          final months = (difference.inDays / 30).floor();
          return '${months}个月前';
        } else {
          final years = (difference.inDays / 365).floor();
          return '${years}年前';
        }
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return dateTime;
    }
  }
}

/// 分享卡片列表组件
class ShareCardList extends StatelessWidget {
  /// 分享数据列表
  final List<ShareCardData> items;

  /// 配置
  final ShareCardConfig config;

  /// 点击回调
  final void Function(ShareCardData data)? onTap;

  /// 收藏切换回调
  final void Function(ShareCardData data)? onFavoriteToggle;

  /// AI分析回调
  final void Function(ShareCardData data)? onAIAnalysis;

  /// 更多操作回调
  final void Function(ShareCardData data)? onMoreActions;

  /// 选择模式
  final bool selectionMode;

  /// 选中的项目IDs
  final Set<String> selectedIds;

  /// 选择切换回调
  final void Function(ShareCardData data)? onToggleSelection;

  /// 高亮查询
  final String? highlightQuery;

  /// 加载状态
  final bool isLoading;

  /// 空状态组件
  final Widget? emptyWidget;

  /// 滚动控制器
  final ScrollController? scrollController;

  const ShareCardList({
    Key? key,
    required this.items,
    this.config = const ShareCardConfig(),
    this.onTap,
    this.onFavoriteToggle,
    this.onAIAnalysis,
    this.onMoreActions,
    this.selectionMode = false,
    this.selectedIds = const {},
    this.onToggleSelection,
    this.highlightQuery,
    this.isLoading = false,
    this.emptyWidget,
    this.scrollController,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (isLoading && items.isEmpty) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (items.isEmpty) {
      return emptyWidget ??
          const Center(
            child: Text('暂无数据'),
          );
    }

    return ListView.builder(
      controller: scrollController,
      itemCount: items.length,
      itemBuilder: (context, index) {
        final item = items[index];
        final isSelected = selectedIds.contains(item.id);

        return ShareCardWidget(
          data: item,
          config: config,
          onTap: () => onTap?.call(item),
          onFavoriteToggle: () => onFavoriteToggle?.call(item),
          onAIAnalysis: () => onAIAnalysis?.call(item),
          onMoreActions: () => onMoreActions?.call(item),
          isSelected: isSelected,
          selectionMode: selectionMode,
          onToggleSelection: () => onToggleSelection?.call(item),
          highlightQuery: highlightQuery,
        );
      },
    );
  }
}
